$(function(){
	//首页加载数据
	searchOrder("All",null,1);
	
	//全部订单查询
	$("#searchAll").on("click",function(){
		searchOrder("All",null,1);
	});
	
	//已支付订单查询
	$("#searchSuccess").on("click",function(){
		searchOrder("Success",1,1);
	});
	
	//未支付订单查询
	$("#searchPay").on("click",function(){
		searchOrder("Pay",0,1);
	});
	
	//已作废订单查询
	$("#searchClose").on("click",function(){
		searchOrder("Close",2,1);
	});
	
	//删除
	checkDelete();
	
	//选项卡事件
	$('#mytab').on('click','li',function(){
		var tab = $.trim($(this).children('a').attr('href'));
		if(tab == "#tab1") {
			searchOrder("All",null,1);
			//删除
			checkDelete();
		}else if(tab == "#tab2") {
			searchOrder("Success",1,1);
			//删除
			checkDelete();
		}else if(tab == "#tab3") {
			searchOrder("Pay",0,1);
			//删除
			checkDelete();
		}else if(tab == "#tab4") {
			searchOrder("Close",2,1);
		}else {
			searchDeleteOrder(1);
			//删除
			checkDelete();
		}
	})
});

//全选删除
function checkDelete(){
	var $all = $('.checkall'),
		$check = $('.checkbox_list');
	
	//清除已选中的全选
	$all.each(function(){
		var $this = $(this);
		$this.prop('checked',false);
	})
	
	$all.on('click',function(){
		var isall = $(this).prop('checked');
		var $next_checklist = $(this).parent().parent().next().find('.checkbox_list');
		if(isall){
			$next_checklist.each(function(){
				var $this = $(this);
				$this.prop('checked',true);
			});
		}else{
			$next_checklist.each(function(){
				var $this = $(this);
				$this.prop('checked',false);
			});
		}
		
	});
	$check.on('click',function(){
		var $this = $(this),
			ischeck = $this.prop('checked'),
			flag = true;
		var $slibings = $this.parents('.orderlistdiv').find('input.checkbox_list');
		if(ischeck){
			$slibings.not($this).each(function(){
				if($(this).prop('checked') == false){
					flag = false;
					return false;
				}
			});
			if(flag == true){
				$this.parents('.orderlist_box').prev().find('input').prop('checked',true);
			}
		}else{
			$this.parents('.orderlist_box').prev().find('input').prop('checked',false);
		}
	});
	//点击删除
	var $delete = $('.delete_btn');
	var delete_state = 0;
	$delete.on('click',function(){
		delete_state = $(this).attr("data-state");
		var orderIds = [],
			temp = null,
			$delete_list = $(this).parents('ul').next().find('input');
		$delete_list.each(function(){
			var $this = $(this),
				$parent= $this.parents('ul');
			if($this.prop('checked') == true){
				temp = $this.parent().next().attr('data-id');
				orderIds.push(temp);
			}
		});
		
		if(orderIds.length > 0) {
			var deleteWarn = "",
				deleteFail = "";
			if(delete_state == 0) {
				deleteWarn = "确定要删除以下订单吗？";
				deleteFail = "删除失败，请重试！";
			}else if(delete_state == 1) {
				deleteWarn = "确定要永久删除以下订单吗？";
				deleteFail = "永久删除失败，请重试！";
			}else {
				deleteWarn = "确定要还原以下订单吗？";
				deleteFail = "还原失败，请重试！";
			}
			
			BSTYUN.dialog.confirm(deleteWarn,function(){
				$.ajax({
					type : "post",
					url : "/consume/order/deleteOrder?orderIds="+orderIds,
					async : false,
					data : {
						deleteState : delete_state
					},
					dataType : "json",
					success : function(data){
						if(data) {
							$delete_list.each(function(){
								var $this = $(this);
								if($this.prop('checked') == true){
									var $parent= $this.parents('ul'),
										state = $.trim($parent.find("li").eq(6).text()),
										i = 0;
									if(state == "待付款"){
										if(i++){}
										else{BSTYUN.dialog.warn("待付款状态不允许删除");}
										return true;
									}
									$parent.remove();
								}
							});
						}else {
							BSTYUN.dialog.warn(deleteFail);
						}
					}
				});
			});
		}else {
			BSTYUN.dialog.warn('请选择要操作的数据！');
		}
		return false;
	});
}


//查询订单数据
function searchOrder(tbs,orderState,page) {
	var params = {
			startTime : $("#startTime"+tbs).val(),
			endTime : $("#endTime"+tbs).val(),
			goodsId : $("#select"+tbs).val(),
			orderState : orderState
	};
	
	$.ajax({
		type : "post",
		url : "/consume/order/search?page="+page,
		async : false,
		data : params,
		dataType : "json",
		success : function(data){
			$('#page'+tbs).val(data.page);
			$('#pageCount'+tbs).val(data.pageCount);
			$('#'+tbs).empty();
			//新增内容
			var tb_content = '';
			if(data.orderList.length > 0) {
				$.each(data.orderList,function(index,order){
					tb_content += '<ul class="cle">'
							   + '<li class="tt"><input type="checkbox" name="checkbox" class="checkbox_list" /></li>'
						 	   + '<li class="tr" data-id="'+order.orderId+'">'+order.orderNum+'</li>' 
							   + '<li>'+order.goodsName+'</li>'
							   + '<li class="td">'+order.count+'</li>'
							   + '<li class="td">'+checkIsFree(order.isFree,order.buyType)+'</li>'
							   + '<li>'+checkPayMoney(order.orderState,order.payMoney,order.orderMoney)+'</li>'
							   + '<li class="td">'+checkOrderState(order.orderState,order.isDredge)+'</li>'
							   + '<li>'+toDate(order.occurTime,"yyyy-MM-dd hh:mm:ss")+'</li>'
							   + '<li>'+checkPayTime(order.payTime)+'</li>'
							   + '<li>'+checkDoState(order.orderState,order.orderId,order.isDredge)+'</li>'
							   + '</ul>';
				})
				
				tb_content += '<div class="page mt20" align="center">共'+data.totalRows+'条记录 '+data.page+'/'+data.pageCount+'页&nbsp;'+
							  '<a href="javascript:searchOrder(\''+tbs+'\','+orderState+',1)">&nbsp;首页</a> <a onclick="javascript:ajaxPageUp(\''+tbs+'\','+orderState+','+data.page+')">上一页</a>&nbsp;'+
							  '<a onclick="javascript:ajaxPageDown(\''+tbs+'\','+orderState+','+data.page+');">&nbsp;下一页</a>&nbsp;'+
							  '<a href="javascript:searchOrder(\''+tbs+'\','+orderState+','+data.pageCount+')" >尾页</a>&nbsp;&nbsp;第&nbsp;&nbsp;'+
							  '<select onchange="ajax2Page(\''+tbs+'\','+orderState+')" id="currPage'+tbs+'" >';
				for(var i = 1; i <= data.pageCount; i++) {
					tb_content += '<option value="'+i+'" ';
					if(data.page == i) {
						tb_content += 'selected="selected"';
					}
					tb_content += '>'+i+'</option>';
				}
				tb_content += '</select>&nbsp;页</div>';
				
			}else {
				tb_content += '<p>没有符合条件的订单，请尝试其他搜索条件。</p>';
			}
			$('#'+tbs).append(tb_content);
		}
	});
}

//跳转到订单详情页面
function toOrderDetail(orderId) {
	location.href="/consume/order/order_detail?orderId="+orderId;
}

//判断操作显示
function checkDoState(state,orderId,isDredge) {
	var str = '',
		state = $.trim(state);
	if(state==null||state==''){
		str = '';
	}else{
		if(state == 1) {
			if(isDredge == 1) {
				str = '<a href="/consume/order/order_detail?orderId='+orderId+'" class="detail">查看详情</a>';
			}else {
				str = '<a href="javascript:void(0)" onclick="dredge(this,'+orderId+')">开通</a><br />'+
				'<a href="/consume/order/order_detail?orderId='+orderId+'" class="detail">查看详情</a>';
			}
		}else if(state == 0) {
			$.ajax({
				type : "post",
				url : "/consume/order/checkOrderIsPayment?orderId="+orderId,
				async : false,
				dataType : "json",
				success : function(data){
					if(data) {
						str = '<a href="/finance/payment">去支付</a>';
					}else {
						str = '<a href="/buy/obligationToPay?orderId='+orderId+'">去支付</a>';
					}
				}
			});
			
			str += ' | <a href="javascript:void(0)" onclick="closeOrder(this,'+orderId+')">作废</a><br />' + 
			      '<a href="/consume/order/order_detail?orderId='+orderId+'" class="detail">查看详情</a>';
		}else if(state == 2) {
			str = '<a href="/consume/order/order_detail?orderId='+orderId+'" class="detail">查看详情</a>';
		}
	}
	return str;
}

//判断订单状态
function checkOrderState(state,isDredge) {
	var str = '',
		state = $.trim(state);
	if(state==null||state==''){
		str = '';
	}else{
		if(state == 1) {
			if(isDredge == 1) {
				str = '已开通';
			}else {
				str = '未开通';
			}
		}else if(state == 0) {
			str = '待付款';
		}else if(state == 2) {
			str = '已作废';
		}
	}
	return str;
}

//判断支付金额
function checkPayMoney(orderState,payMoney,orderMoney) {
	var str = '';
	if(orderState == 1){
		str = parseFloat(payMoney).toFixed(2);
	}else{
		str = parseFloat(orderMoney).toFixed(2);
	}
	return str;
}

//判断购买类型
function checkIsFree(isFree,buyType) {
	var str = '';
	isFree = $.trim(isFree);
	if(isFree == null || isFree==''){
		str = '&nbsp;';
	}else{
		if(isFree == 0) {
			if(buyType == 0) {
				str = '购买';
			}else if(buyType == 1) {
				str = '续费';
			}else {
				str = '升级';
			}
		}else if(isFree == 1) {
			str = '试用';
		}
	}
	return str;
}

//判断付款时间
function checkPayTime(payTime) {
	var str = '';
	if(payTime==null||payTime==''){
		str = '&nbsp;';
	}else{
		str = toDate(payTime,"yyyy-MM-dd hh:mm:ss")
	}
	return str;
}

//直接查询某页
function ajax2Page(tbs,orderState) {
	searchOrder(tbs,orderState,$('#currPage'+tbs).val());
}

//向上翻页
function ajaxPageUp(tbs,orderState,page) {
	if(page == 1) {
		BSTYUN.dialog.warn("已经是第一页");
		return;
	}else {
		var num = parseInt(page) - 1;
		searchOrder(tbs,orderState,num);
	}
}

//向下翻页
function ajaxPageDown(tbs,orderState,page) {
	if(page == $("#pageCount"+tbs).val()) {
		BSTYUN.dialog.warn("已经是最后一页");
		return;
	}else {
		var num = parseInt(page) + 1;
		searchOrder(tbs,orderState,num);
	}
}


//作废订单
function closeOrder(that,orderId) {
	var $this = $(that);
	var flag = $this.parent().parent().parents('div').attr('id');
	
	BSTYUN.dialog.confirm("确定要作废此订单吗？",function(){
		$.ajax({
			type : "post",
			url : "/consume/order/closeOrder?orderId="+orderId,
			async : false,
			dataType : "json",
			success : function(data){
				if(data) {
					if(flag == 'All') {
						searchOrder("All",null,1);
					}else {
						$this.parent().parents('ul').remove();
					}
				}else {
					BSTYUN.dialog.warn("作废失败，请重试！");
				}
			}
		});
	});
}


//开通应用
function dredge(that,orderId){
	var $this = $(that);
	var flag = $this.parent().parent().parents('div').attr('id');
	$.ajax({
		type : "post",
		url : "/eos/dredgeApply?orderId="+orderId,
		dataType : "json",
		beforeSend : function() {
			var loading = function(html,callback){
		        var dialog = null;
		        dialog = $.dialog({
		            id: 'loading',
		            fixed:true,
		            title:false,
		            lock:true,
		            padding:'10px 20px',
		            content: '<div class="loading-tip">'+html+'</div>'
		        });
		    }
			loading('<span style="color:red;font-size:16px;">开通正在进行,时长约为1分钟！请耐心等待！<br>开通成功后，页面会自动刷新！</span>');
		},
		success : function(data){
			BSTYUN.dialog.close("loading");
			if(data) {
				if(flag == 'All') {
					searchOrder("All",null,1);
				}else {
					searchOrder("Success",1,1);
				}
			}else {
				BSTYUN.dialog.warn("网络异常，开通失败，请重试！");
			}
		},
		error : function() {
			BSTYUN.dialog.close("loading");
			BSTYUN.dialog.warn("网络错误，请稍后重试！");
		}
	})
}
